/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package LDAPConn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.ErrorResultException;
import org.forgerock.opendj.ldap.ErrorResultIOException;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.SearchResultReferenceIOException;
import org.forgerock.opendj.ldap.SearchScope;
import org.forgerock.opendj.ldap.responses.SearchResultEntry;
import org.forgerock.opendj.ldap.responses.SearchResultReference;
import org.forgerock.opendj.ldap.schema.Schema;
import org.forgerock.opendj.ldif.ConnectionEntryReader;

/**
 *
 * @author anvil
 */
public class LDAPBroker {

    private static LDAPBroker lb;

    //Connection variables
    private Connection connection;
    private Schema schema;
    private String url;
    private int port;
    private String baseDN;

    private LDAPBroker() {

    }

    public static LDAPBroker getLDAPBroker() {
        if (LDAPBroker.lb == null) {
            LDAPBroker.lb = new LDAPBroker();
        }

        return LDAPBroker.lb;
    }

    public List<Entry> search(String s) {
        return null;
    }

    public boolean add(HashMap<String, String> s) {
        return false;
    }

    public boolean terminate(HashMap<String, String> s) {
        return false;
    }

    public void setConnectionDetails(String url, int port, String baseDN) {
        this.url = url;
        this.port = port;
        this.baseDN = baseDN;
    }

    public boolean connect() {
        try {
            final LDAPConnectionFactory factory = new LDAPConnectionFactory(url, port);

            this.connection = factory.getConnection();
            this.schema = Schema.readSchemaForEntry(connection, DN.valueOf(this.baseDN));

            return true;
        } catch (ErrorResultException e) {
            return false;
        }
    }

    public List<Entry> getAllEntries() {
        List<Entry> entries = new ArrayList();

        try {
            final ConnectionEntryReader reader = connection.search("dc=example,dc=com", SearchScope.WHOLE_SUBTREE, "(cn=*)", "*");
            
            while (reader.hasNext()) {
                if (reader.isEntry()) {
                    final SearchResultEntry entry = reader.readEntry();
                    entries.add(new Entry(entry));
                }
            }
        } catch (ErrorResultIOException | SearchResultReferenceIOException e) {
            e.printStackTrace();
        }

        return entries;
    }

    public boolean disconnect() {
        if (connection != null) {
            connection.close();
            return true;
        }
        return false;
    }
}
